
import { decorator } from '@/tools/fns/decorator';
import * as XLSX from 'xlsx';
import { DatePicker, Divider, Form, Table, Typography, type TableColumnType, Button } from '@/components/base';
import { observer } from 'mobx-react';
import React from 'react';
import dayjs from 'dayjs';
import { Controller } from '@/controller';
import classnames from 'classnames';
import styles from './index.module.less';
import { useNavigate } from 'react-router-dom';

const { Text } = Typography;

const Entering = decorator(observer)(function () {

    const controller = React.useContext(Controller.Context);
    const { data } = controller;
    const navigate = useNavigate();
    const [values, setValues] = React.useState<{ date?: dayjs.Dayjs }>({});
    const [form] = Form.useForm<typeof values>();
    const date = React.useMemo(() => values?.date, [values?.date]);
    const month = date?.month() || 0;

    const columns = React.useCallback((range: [dayjs.Dayjs, dayjs.Dayjs]): TableColumnType[] => {
        const days = rangeToDays(range);
        if (!date) return [];

        return [
            ...days.map((e, i) => {
                const isEven = i % 2 === 0;
                const isToday = e.isSame(dayjs(), 'day');
                return {
                    title: (
                        <div>
                            <Button type='link' style={{fontWeight: 'bold'}} onClick={()=>{navigate(`/dailySummary?day=${e.format('YYYYMMDD')}`)}} >{e.format('MM-DD')}</Button>
                            <div>{e.format('dd')}{isToday && <Text type='danger'>(今)</Text>}</div>
                        </div>
                    ),
                    className: classnames({ [styles['table-zz']]: isEven }),
                    children: [
                        {
                            title: '新客',
                            align: 'center',
                            dataIndex: [e.format('YYYYMMDD'), 'newCustomer'],
                            key: e.format('YYYYMMDD') + '-newCustomer',
                            className: classnames({ [styles['table-zz']]: isEven }),
                            width: 45,
                        },
                        {
                            title: '会员',
                            align: 'center',
                            dataIndex: [e.format('YYYYMMDD'), 'member'],
                            key: e.format('YYYYMMDD') + '-member',
                            className: classnames({ [styles['table-zz']]: isEven }),
                            width: 45,
                        },
                        {
                            title: '客次',
                            align: 'center',
                            dataIndex: [e.format('YYYYMMDD'), 'customer'],
                            key: e.format('YYYYMMDD') + '-customer',
                            className: classnames({ [styles['table-zz']]: isEven }),
                            width: 45,
                        },
                    ]
                } as TableColumnType
            })
        ]
    }, [date, navigate])

    const dataSource = React.useCallback((stage: string, range: [dayjs.Dayjs, dayjs.Dayjs]) => {
        const { turnover = [] } = data;
        const days = rangeToDays(range);
        const values: any = {};
        days.forEach(e => {
            const t = turnover.filter(item => {
                return toXlsxDay(item['日期']).format('YYYYMMDD') === e.format('YYYYMMDD');
            });

            const newCustomer = (() => {
                const n = t.filter(item => item['客户类型'] === '新客').map(e => e['客户名称']);
                const s = [...new Set(n)];
                return s.length || 0;
            })()

            const member = (() => {
                const n = t.filter(item => item['客户类型'] === '会员').map(e => e['客户名称']);
                const s = [...new Set(n)];
                return s.length || 0;
            })()

            values[e.format('YYYYMMDD')] = {
                newCustomer,
                member,
                customer: newCustomer + member
            };
        });
        return [{
            stage,
            ...values,
        }]
    }, [data]);

    // 设置当前月
    React.useEffect(() => {
        if (!values.date) {
            const now = dayjs();
            form.setFieldsValue({ date: now });
            setValues({ date: now });
        }
    }, [form, values.date]);

    return (
        <div style={{ padding: 20 }}>
            <Form form={form} layout='inline' onValuesChange={(_, e) => { setValues(e) }} >
                <Form.Item label="日期" name="date">
                    <DatePicker picker='month' />
                </Form.Item>
            </Form>

            <Divider />

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }} >
                <div style={{ display: 'flex' }} >
                    <div style={{ width: 90, flex: 'none', display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', background: '#fff' }}>
                        <Text strong>阶段一</Text>
                        <div>（共{dayjs(`2025-${month+1}-2`).diff(dayjs(`2025-${month}-26`), 'day') + 1}天）</div>
                    </div>
                    <div style={{ flex: 'none' }} >
                        <Table
                            bordered
                            size='small'
                            columns={columns([dayjs(`2025-${month}-26`), dayjs(`2025-${month + 1}-02`)])}
                            pagination={false}
                            dataSource={dataSource('阶段一', [dayjs(`2025-${month}-26`), dayjs(`2025-${month + 1}-02`)])}
                        />
                    </div>
                </div>

                <div style={{ display: 'flex' }} >
                    <div style={{ width: 90, flex: 'none', display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', background: '#fff' }}>
                        <Text strong>阶段二</Text>
                        <div>（共7天）</div>
                    </div>
                    <div style={{ flex: 'none' }} >
                        <Table
                            bordered
                            size='small'
                            columns={columns([dayjs(`2025-${month + 1}-03`), dayjs(`2025-${month + 1}-09`)])}
                            pagination={false}
                            dataSource={dataSource('阶段二', [dayjs(`2025-${month + 1}-03`), dayjs(`2025-${month + 1}-09`)])}
                        />
                    </div>
                </div>

                <div style={{ display: 'flex' }} >
                    <div style={{ width: 90, flex: 'none', display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', background: '#fff' }}>
                        <Text strong>阶段三</Text>
                        <div>（共7天）</div>
                    </div>
                    <div style={{ flex: 'none' }} >
                        <Table
                            bordered
                            size='small'
                            columns={columns([dayjs(`2025-${month + 1}-10`), dayjs(`2025-${month + 1}-16`)])}
                            pagination={false}
                            dataSource={dataSource('阶段三', [dayjs(`2025-${month + 1}-10`), dayjs(`2025-${month + 1}-16`)])}
                        />
                    </div>
                </div>

                <div style={{ display: 'flex' }} >
                    <div style={{ width: 90, flex: 'none', display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', background: '#fff' }}>
                        <Text strong>阶段四</Text>
                        <div>（共7天）</div>
                    </div>
                    <div style={{ flex: 'none' }} >
                        <Table
                            bordered
                            size='small'
                            columns={columns([dayjs(`2025-${month + 1}-17`), dayjs(`2025-${month + 1}-23`)])}
                            pagination={false}
                            dataSource={dataSource('阶段四', [dayjs(`2025-${month + 1}-17`), dayjs(`2025-${month + 1}-23`)])}
                        />
                    </div>
                </div>

                <div style={{ display: 'flex' }} >
                    <div style={{ width: 90, flex: 'none', display: 'flex', flexDirection: 'column', justifyContent: 'center', textAlign: 'center', background: '#fff' }}>
                        <Text strong>阶段五</Text>
                        <div>（共2天）</div>
                    </div>
                    <div style={{ flex: 'none' }} >
                        <Table
                            bordered
                            size='small'
                            columns={columns([dayjs(`2025-${month + 1}-24`), dayjs(`2025-${month + 1}-25`)])}
                            pagination={false}
                            dataSource={dataSource('阶段五', [dayjs(`2025-${month + 1}-24`), dayjs(`2025-${month + 1}-25`)])}
                        />
                    </div>
                </div>
            </div>
        </div>
    )
})
export default Entering;


/** 时间范围 to 日期列表 */
function rangeToDays(range: [dayjs.Dayjs, dayjs.Dayjs]): dayjs.Dayjs[] {
    let p = range[0].clone();
    const r = [range[0].clone()];
    for (; p.valueOf() < range[1].valueOf();) {
        p = p.add(1, 'day');
        r.push(p.clone())
    }
    return r;
}

function toXlsxDay(params: any) {
    return dayjs(XLSX.SSF.format("yyyy-mm-dd", params))
}